<template>
	<view class="p-login">
		<uni-forms ref="formRef" :modelValue="formData" :rules="formRules">
			<uni-forms-item label="username" name="username">
				<input type="text" v-model="formData.username"/>
			</uni-forms-item>
			<uni-forms-item label="password" name="password">
				<input type="password" v-model="formData.password"/>
			</uni-forms-item>
		</uni-forms>
		<button type="default" @click="onSubmit">登录</button>
		<button @click="useWechatLogin">微信账号登录</button>
	</view>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { getOpenIdAPI } from "./api";
import { useIndexStore } from "@/store";

const indexSe = useIndexStore();

const formRef = ref<any>(null);
const formData = ref({
	username: '',
	password: ''
})

const formRules: any = ref({
	username: {
		rules: [{
			required: true,
			errorMessage: '请输入用户名'
		}]
	},
	password: {
		rules: [{
			required: true,
			errorMessage: '请输入密码'
		}, {
			// 自定义校验规则
			// validateFunction: function(rule, value, data, callback) {
			// 	if (value !== '123') {
			// 		callback('请输入123')
			// 	}
			// 	return true
			// }
		}]
	}
})

const onSubmit = () => {
	formRef.value.validate().then((res: any) => {
		console.log('success', res);
		uni.showToast({
			title: `校验通过`
		})
	}).catch((err: any) => {
		console.log('err', err);
	})
}

const useWechatLogin = async() => {
	try {
		const wxLoginRes: any = await indexSe.wxLogin();
		try {
			const getOpenIdRes: any = await getOpenIdAPI({ code: wxLoginRes.code });
			console.log('服务器返回的 openid 和 session_key:', getOpenIdRes.data);
		} catch(err) {
			console.log('获取 openid 失败:', err);
		}
	} catch(err) {
		console.log('获取 wx 临时 code 失败:', err);
	}
}

onMounted(() => {
	formRef?.value?.setRules(formRules.value);
})
</script>

<style scoped>
.p-login {
	
}
</style>